﻿<template>
    <div class="light-chat-container">
        <!-- 中间聊天列表 -->
            <div class="chat-list">
            <div class="chat-list-header">
                <h1>收件箱</h1>
            </div>


            <div class="chat-list-content">
                <!-- 加载中状态 -->
                <div v-if="loading" class="loading-conversations">
                    <div class="loading-spinner">
                        <svg viewBox="0 0 50 50" class="spinner">
                            <circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="4"></circle>
                        </svg>
                    </div>
                    <div class="loading-text">加载会话中...</div>
                </div>

                <!-- 无会话状态 -->
                <div v-else-if="conversations.length === 0" class="empty-conversations">
                    <div class="empty-icon">
                        <svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="#8E8E93" stroke-width="1">
                            <rect x="2" y="4" width="20" height="16" rx="2"/>
                            <path d="M12 4v16" stroke-linecap="round"/>
                            <path d="M15 10h4" stroke-linecap="round"/>
                            <path d="M15 14h4" stroke-linecap="round"/>
                            <path d="M5 10h4" stroke-linecap="round"/>
                            <path d="M5 14h4" stroke-linecap="round"/>
                        </svg>
                    </div>
                    <div class="empty-text">暂无会话</div>
                    <div class="empty-hint">您可以通过商品或求购页面联系卖家/买家</div>
                </div>

                <!-- 会话列表 -->
                <template v-else>
                    <!-- 置顶会话区域 -->
                    <template v-if="pinnedConversationsList.length > 0">
            <div class="pinned-section">
                <div class="pinned-label">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                        <path d="M14 4v7l2 2v1H8v-1l2-2V4" stroke="#8E8E93" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M12 18v3" stroke="#8E8E93" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    <span>已置顶</span>
                </div>
            </div>

                        <!-- 置顶会话列表 -->
                        <div 
                            v-for="conversation in pinnedConversationsList" 
                            :key="conversation.id"
                            class="chat-item" 
                            :class="{ 'active': currentConversation && currentConversation.id === conversation.id, 'pinned': true }"
                            @click="selectConversation(conversation)"
                        >
                    <div class="chat-avatar">
                                <img 
                                    :src="conversation.partnerAvatar && conversation.partnerAvatar.startsWith('http')
                                        ? conversation.partnerAvatar
                                        : (conversation.partnerAvatar
                                            ? `/images/user/${conversation.partnerAvatar}`
                                            : getDefaultAvatar(conversation.partnerId))" 
                                    :alt="conversation.partnerName || userNames[conversation.partnerId] || '用户' + conversation.partnerId" 
                                />
                    </div>
                        <div class="chat-info">
                        <div class="chat-name-row">
                                    <span class="chat-name">{{ conversation.partnerName || userNames[conversation.partnerId] || '用户' + conversation.partnerId }}</span>
                                    <span class="chat-time">{{ formatMessageTime(conversation.updatedAt) }}</span>
                            </div>
                                <div class="chat-preview">
                                    {{ conversation.lastMessage ? (conversation.lastMessage.type === 'product' ? '[商品]' : formatMessageContent(conversation.lastMessage.content)) : '暂无消息' }}
                            </div>
                        </div>
                            <div v-if="conversation.unreadCount > 0" class="chat-badge unread">
                                {{ conversation.unreadCount > 99 ? '99+' : conversation.unreadCount }}
                    </div>
                            <div v-else-if="conversation.lastMessage && conversation.lastMessage.senderId === currentUserId" class="status-icon">
                                <svg v-if="conversation.lastMessage.status === 'read'" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#58AEFF" stroke-width="2">
                                    <path d="M4 12l5 5L19 7" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                                <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8E8E93" stroke-width="2">
                                    <path d="M4 12l5 5L19 7" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                </div>
                    </div>
                        
                        <!-- 其他会话分隔 -->
                        <div class="conversations-divider">
                            <span>其他会话</span>
            </div>
                    </template>
                    
                    <!-- 普通会话列表 -->
                    <div 
                        v-for="conversation in normalConversationsList" 
                        :key="conversation.id"
                        class="chat-item" 
                        :class="{ 'active': currentConversation && currentConversation.id === conversation.id }"
                        @click="selectConversation(conversation)"
                    >
                    <div class="chat-avatar">
                            <img 
                                :src="conversation.partnerAvatar && conversation.partnerAvatar.startsWith('http')
                                    ? conversation.partnerAvatar
                                    : (conversation.partnerAvatar
                                        ? `/images/user/${conversation.partnerAvatar}`
                                        : getDefaultAvatar(conversation.partnerId))" 
                                :alt="conversation.partnerName || userNames[conversation.partnerId] || '用户' + conversation.partnerId" 
                            />
                        </div>
                    <div class="chat-info">
                        <div class="chat-name-row">
                                <span class="chat-name">{{ conversation.partnerName || userNames[conversation.partnerId] || '用户' + conversation.partnerId }}</span>
                                <span class="chat-time">{{ formatMessageTime(conversation.updatedAt) }}</span>
                    </div>
                            <div class="chat-preview">
                                {{ conversation.lastMessage ? (conversation.lastMessage.type === 'product' ? '[商品]' : formatMessageContent(conversation.lastMessage.content)) : '暂无消息' }}
                    </div>
                </div>
                        <div v-if="conversation.unreadCount > 0" class="chat-badge unread">
                            {{ conversation.unreadCount > 99 ? '99+' : conversation.unreadCount }}
                        </div>
                        <div v-else-if="conversation.lastMessage && conversation.lastMessage.senderId === currentUserId" class="status-icon">
                            <svg v-if="conversation.lastMessage.status === 'read'" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#58AEFF" stroke-width="2">
                                <path d="M4 12l5 5L19 7" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                            <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8E8E93" stroke-width="2">
                                <path d="M4 12l5 5L19 7" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </div>
                </div>
                </template>
            </div>
        </div>

        <!-- 中间聊天内容区域 -->
        <div class="chat-detail">
            <div class="chat-detail-header">
                <div class="header-left">
                    <div class="user-info">
                        <div class="user-avatar">
                            <img 
                                :src="currentConversation?.partnerAvatar && currentConversation.partnerAvatar.startsWith('http')
                                    ? currentConversation.partnerAvatar
                                    : (currentConversation?.partnerAvatar 
                                        ? `/images/user/${currentConversation.partnerAvatar}`
                                        : (currentConversation?.partnerId ? getDefaultAvatar(currentConversation.partnerId) : ''))" 
                                :alt="currentConversation?.partnerName || '未知用户'" 
                            />
                        </div>
                        <div class="user-name-container">
                            <div class="user-name">{{ currentConversation?.partnerName || (currentConversation?.partnerId && userNames[currentConversation.partnerId]) || '未知用户' }}</div>
                            <div class="user-status">{{ currentConversation ? (formatTimeAgo(Array.isArray(currentConversation.updatedAt) ? currentConversation.updatedAt : new Date(currentConversation.updatedAt))) + '活跃' : '暂无会话' }}</div>
                        </div>
                    </div>
                </div>
                <div class="header-actions">
                    <button class="icon-btn call-btn" @click="handleCall">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                            <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13 1 .3 2 .54 2.91a2 2 0 01-.45 2.1L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.92.25 1.92.42 2.91.55A2 2 0 0122 16.92z" stroke="#FFFFFF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </button>
                    <button class="icon-btn menu-btn" @click="toggleChatMenu">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
  <circle cx="12" cy="10" r="3"></circle>
</svg>
                    </button>
                </div>
            </div>

            <div class="messages-container" ref="messagesContainer">
                <div class="date-separator">
                    <span>今天</span>
                </div>

                <!-- 动态渲染消息列表 -->
                <template v-for="(message, index) in messages" :key="message.id">
                    <!-- 消息行 -->
                    <div class="message-row" :class="{ 'sent-row': message.type === 'sent' }">
                        <!-- 头像 -->
                        <div class="message-avatar">
                            <img 
                                :src="message.type === 'sent' 
                                    ? (userStore.userInfo?.avatar && userStore.userInfo.avatar.startsWith('http')
                                        ? userStore.userInfo.avatar 
                                        : (userStore.userInfo?.avatar 
                                            ? `/images/user/${userStore.userInfo.avatar}`
                                            : getDefaultAvatar(currentUserId)))
                                    : (currentConversation?.partnerAvatar && currentConversation.partnerAvatar.startsWith('http')
                                        ? currentConversation.partnerAvatar
                                        : (currentConversation?.partnerAvatar
                                            ? `/images/user/${currentConversation.partnerAvatar}`
                                            : getDefaultAvatar(currentConversation?.partnerId || 0)))" 
                                :alt="message.type === 'sent' ? '我' : (currentConversation?.partnerName || '用户')" 
                            />
                        </div>
                        
                        <!-- 消息内容 -->
                        <div class="message-column">
                            <div class="message-header">
                                <span class="sender-name">{{ message.type === 'sent' ? '你' : (currentConversation?.partnerName || userNames[currentConversation?.partnerId || 0] || '用户') }}</span>
                                <span class="message-time">{{ message.timestamp }}</span>
                            </div>
                            
                            <!-- 普通消息 -->
                            <div v-if="!message.isProduct && message.content" class="message-bubble" :class="message.type">
                                {{ formatMessageContent(message.content) }}
                            </div>
                            
                            <!-- 商品消息 -->
                            <div v-if="message.isProduct" class="product-message" @click="message.isPurchaseRequest ? goToPurchaseRequestDetail(message.product) : goToProductDetail(message.product)">
                                <div class="product-message-content" :class="{'purchase-request': message.isPurchaseRequest}">
                                    <img class="product-image" :src="message.product?.image || `https://api.dicebear.com/7.x/shapes/svg?seed=product&backgroundColor=2980b9`" :alt="message.product?.name || '商品'" />
                                    <div class="product-info">
                                        <div class="product-header">
                                            <div class="product-name">{{ message.product?.name || '商品' }}</div>
                                            <div class="product-price-tag" v-if="message.product?.price">{{ message.product.price }}</div>
                                            <div class="product-price-tag" v-else>¥待议</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>

            <div class="message-input-area">
                <button class="input-icon-btn">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                        <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M19 10v2a7 7 0 0 1-14 0v-2" stroke-linecap="round" stroke-linejoin="round"/>
                        <line x1="12" y1="19" x2="12" y2="22" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
                <div class="message-input-container">
                    <input 
                        type="text" 
                        v-model="messageInput" 
                        @keyup.enter="sendMessage()"
                        placeholder="想聊点什么..." 
                        class="message-input" 
                    />
                </div>
                <!-- 新增表情包按钮 -->
                <button class="input-icon-btn emoji-btn" @click="toggleEmojiPanel">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                        <circle cx="12" cy="12" r="10"/>
                        <path d="M8 14s1.5 2 4 2 4-2 4-2" stroke-linecap="round"/>
                        <circle cx="9" cy="9" r="1" fill="#007AFF"/>
                        <circle cx="15" cy="9" r="1" fill="#007AFF"/>
                    </svg>
                </button>
                <button class="input-icon-btn feature-toggle-btn" :class="{'active': showFeaturePanel}" @click="toggleFeaturePanel">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                        <circle cx="12" cy="12" r="10"/>
                        <line x1="12" y1="8" x2="12" y2="16" stroke-linecap="round"/>
                        <line x1="8" y1="12" x2="16" y2="12" stroke-linecap="round"/>
                    </svg>
                </button>
            </div>

            <!-- 表情面板 -->
            <div class="emoji-panel" v-show="showEmojiPanel">
                <div class="emoji-grid">
                    <div class="emoji-item" v-for="emoji in emojis" :key="emoji" @click="insertEmoji(emoji)">
                        {{ emoji }}
                    </div>
                </div>
            </div>

            <!-- 功能面板 -->
            <div class="feature-panel" v-show="showFeaturePanel">
                <div class="feature-grid">
                    <div class="feature-item">
                        <div class="feature-icon">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                                <rect x="3" y="3" width="18" height="18" rx="3"/>
                                <circle cx="8.5" cy="8.5" r="1.5" fill="#007AFF"/>
                                <path d="M6 16l3-3 2 2 4-4 3 3" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </div>
                        <span>相册</span>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                                <circle cx="12" cy="12" r="7"/>
                                <circle cx="12" cy="12" r="3"/>
                                <circle cx="16.5" cy="7.5" r="1" fill="#007AFF"/>
                            </svg>
                        </div>
                        <span>拍摄</span>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                                <rect x="2" y="4" width="20" height="16" rx="2"/>
                                <path d="M12 4v16" stroke-linecap="round"/>
                                <path d="M15 10h4" stroke-linecap="round"/>
                                <path d="M15 14h4" stroke-linecap="round"/>
                                <path d="M5 10h4" stroke-linecap="round"/>
                                <path d="M5 14h4" stroke-linecap="round"/>
                            </svg>
                        </div>
                        <span>发送商品</span>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                                <rect x="3" y="5" width="18" height="14" rx="2"/>
                                <path d="M8 9h8" stroke-linecap="round"/>
                                <path d="M8 13h5" stroke-linecap="round"/>
                                <path d="M8 17h3" stroke-linecap="round"/>
                            </svg>
                        </div>
                        <span>推荐名片</span>
                    </div>
                </div>
                <div class="feature-grid">
                    <div class="feature-item">
                        <div class="feature-icon">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                                <circle cx="12" cy="12" r="10"/>
                                <circle cx="12" cy="9" r="1" fill="#007AFF"/>
                                <path d="M8 14h8" stroke-linecap="round"/>
                                <path d="M8 17h5" stroke-linecap="round"/>
                            </svg>
                        </div>
                        <span>特殊</span>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                                <path d="M21 10c0 5.523-4.477 10-10 10S1 15.523 1 10 5.477 0 12 0s9 4.477 9 10z" transform="translate(1 2)"/>
                                <circle cx="12" cy="12" r="3"/>
                            </svg>
                        </div>
                        <span>发送位置</span>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#007AFF" stroke-width="1.5">
                                <path d="M18 8A6 6 0 106 8c0 7-3 9-3 9h18s-3-2-3-9z" stroke-linecap="round" stroke-linejoin="round"/>
                                <path d="M12 21v-3" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </div>
                        <span>设置提醒</span>
                    </div>
                    <div class="feature-item" style="visibility: hidden;">
                        <!-- 占位 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧个人资料区域 -->
        <div class="profile-sidebar">
            <div class="profile-header">
                <button class="icon-btn" style="visibility: hidden;">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                        <circle cx="12" cy="6" r="1.5" fill="#8E8E93"/>
                        <circle cx="12" cy="12" r="1.5" fill="#8E8E93"/>
                        <circle cx="12" cy="18" r="1.5" fill="#8E8E93"/>
                    </svg>
                </button>
                <h2>个人资料</h2>
                <button class="icon-btn menu-btn" @click="toggleProfileMenu">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                        <circle cx="12" cy="6" r="1.5" fill="#8E8E93"/>
                        <circle cx="12" cy="12" r="1.5" fill="#8E8E93"/>
                        <circle cx="12" cy="18" r="1.5" fill="#8E8E93"/>
                    </svg>
                </button>
            </div>

            <div class="profile-content">
                <!-- 个人信息部分 -->
                <div class="profile-info">
                    <div v-if="userProfileLoading" class="profile-loading">
                        <div class="loading-spinner">
                            <svg viewBox="0 0 50 50" class="spinner">
                                <circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="4"></circle>
                            </svg>
                        </div>
                        <div class="loading-text">加载用户资料中...</div>
                    </div>
                    <div v-else class="profile-info-header">
                        <img class="profile-avatar-img" 
                            :src="userProfile?.avatar ? (userProfile.avatar.startsWith('http') 
                                    ? userProfile.avatar 
                                    : `/images/user/${userProfile.avatar}`) 
                                : (currentConversation?.partnerId ? getDefaultAvatar(currentConversation?.partnerId) : '')" 
                            :alt="userProfile?.nickname || userProfile?.username || '未知用户'" />
                        <h3 class="profile-name">{{ userProfile?.nickname || userProfile?.username || '未知用户' }}</h3>
                        <p class="profile-university">{{ userProfile?.school || '未知学校' }}</p>
                    </div>
                </div>

                <!-- 个人中心按钮 - 移到这里，放在个人信息和消息设置之间 -->
                <button class="profile-center-btn" @click="visitPersonalCenter">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="1.5">
                        <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/>
                        <circle cx="12" cy="7" r="4"/>
                    </svg>
                    <span>访问个人中心</span>
                </button>

                <!-- 消息设置 - 放在个人中心按钮后面 -->
                <div class="profile-section">
                    <h4 class="section-title">消息设置</h4>
                    <div class="settings-list">
                        <div class="settings-row">
                            <span>免打扰</span>
                            <label class="toggle-switch">
                                <input type="checkbox" v-model="muteNotifications">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        <div class="settings-row">
                            <span>置顶会话</span>
                            <label class="toggle-switch">
                                <input type="checkbox" v-model="isPinned" @change="togglePinConversation">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        <div class="settings-row block-user-row" @click="handleBlockUser">
                            <span>拉黑用户</span>
                            <div class="block-action-wrapper">
                                <el-icon class="block-user-warning-icon"><WarningFilled /></el-icon>
                                <label class="toggle-switch block-user-switch">
                                    <input type="checkbox" disabled>
                                    <span class="toggle-slider"></span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 个人详细信息 -->
                <div class="profile-section">
                    <h4 class="section-title">关于</h4>
                    <p class="section-content">{{ userProfile?.introduction || '这个用户很懒，什么也没留下。' }}</p>
                </div>

                <div class="profile-section">
                    <h4 class="section-title">联系方式</h4>
                    <div class="contact-info">
                        <div class="contact-item">
                            <div class="contact-icon">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#0055FF" stroke-width="1.5">
                                    <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13 1 .3 2 .54 2.91a2 2 0 01-.45 2.1L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.92.25 1.92.42 2.91.55A2 2 0 0122 16.92z"/>
                                </svg>
                            </div>
                            <span>{{ userProfile?.phone || '未知' }}</span>
                        </div>
                        <div class="contact-item">
                            <div class="contact-icon">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#0055FF" stroke-width="1.5">
                                    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"></path>
                                    <circle cx="12" cy="10" r="3"></circle>
                                </svg>
                            </div>
                            <span>{{ userProfile?.region || '未知地区' }}</span>
                        </div>
                    </div>
                </div>

                <!-- 商品概览 -->
                <div class="profile-section" v-if="userProducts.length > 0">
                    <h4 class="section-title">正在出售 ({{ userProductsCount }})</h4>
                    <div class="products-gallery">
                        <div class="product-item" v-for="product in userProducts" :key="product.id">
                            <img :src="product.images?.[0] || product.image || `https://api.dicebear.com/7.x/shapes/svg?seed=${product.id}&backgroundColor=2980b9`" 
                                :alt="product.title || product.name || '商品'" />
                            <div class="product-overlay">
                                <span class="product-price">¥{{ product.price }}</span>
                            </div>
                        </div>
                    </div>
                    <button class="view-all-btn" @click="viewAllProducts">
                        <span>查看更多商品</span>
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#0055FF" stroke-width="1.5">
                            <path d="M9 18l6-6-6-6" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, onUnmounted, watch, nextTick, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import {
  getChatConversations,
  getChatMessages,
  sendChatMessage,
  sendProductCard,
  markConversationAsRead,
  deleteConversation,
  createConversation,
  type ChatConversation as ChatApiConversation,
  type ChatMessage as ChatApiMessage
} from '@/api/chat'
import { blockUser } from '@/api/user'
import request from '@/utils/request'
import notificationService from '@/utils/notification'
import { WarningFilled } from '@element-plus/icons-vue'
import type { UserProfile } from '@/api/user'
import type { ChatMessage, ChatConversation } from '@/types/chat'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const currentUserId = ref(userStore.userInfo?.id || 0)
const messagesContainer = ref<HTMLElement | null>(null)
const messageInput = ref('')
const muteNotifications = ref(false)
const muteSounds = ref(false)
const showFeaturePanel = ref(false)
const showEmojiPanel = ref(false)
const loading = ref(false)
const messagesLoading = ref(false)
const conversations = ref<ChatConversation[]>([])
const currentConversation = ref<ChatConversation | null>(null)
const showChatMenu = ref(false)
const showProfileMenu = ref(false)

// 添加置顶会话状态
const pinnedConversations = ref<number[]>([]) // 存储置顶会话的ID

// 添加计算属性判断当前会话是否已置顶
const isPinned = computed(() => {
  if (!currentConversation.value) return false;
  return pinnedConversations.value.includes(currentConversation.value.id);
});

// 计算已置顶的会话列表
const pinnedConversationsList = computed(() => {
  return conversations.value.filter(conv => 
    pinnedConversations.value.includes(conv.id)
  );
});

// 计算未置顶的会话列表
const normalConversationsList = computed(() => {
  return conversations.value.filter(conv => 
    !pinnedConversations.value.includes(conv.id)
  );
});

// 表情包列表
const emojis = ['😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😍', '😘', '😗', '😙', '😚', '🙂', '🤗', '🤔', '👍', '👎', '👌', '✌️', '🤞', '🙏', '👏', '👋']

// 插入表情到输入框
const insertEmoji = (emoji: string) => {
  messageInput.value += emoji
  showEmojiPanel.value = false
}

// 切换表情面板显示
const toggleEmojiPanel = () => {
  showEmojiPanel.value = !showEmojiPanel.value
  if (showEmojiPanel.value) {
    showFeaturePanel.value = false
  }
  // 添加动画类触发按钮动画
  const emojiBtn = document.querySelector('.emoji-btn') as HTMLElement;
  if (showEmojiPanel.value) {
    emojiBtn?.classList.add('active');
  } else {
    emojiBtn?.classList.remove('active');
  }
}

// 切换功能面板
const toggleFeaturePanel = () => {
  showFeaturePanel.value = !showFeaturePanel.value;
  if (showFeaturePanel.value) {
    showEmojiPanel.value = false;
  }
}

// 访问个人中心
const visitPersonalCenter = () => {
  // 获取当前用户ID，如果是查看别人的资料，则传递对话伙伴的ID
  const userId = currentConversation.value?.partnerId || userStore.userInfo?.id;
  
  // 导航到个人中心并传递用户ID参数
  router.push(`/user/center?userId=${userId}`);
}

// 跳转到商品详情
const goToProductDetail = (product: any) => {
  if (product && product.productId) {
    router.push(`/product/detail?id=${product.productId}`);
  } else if (product && product.name) {
    router.push(`/product/detail?name=${encodeURIComponent(product.name)}`);
  }
}

// 搜索功能
const handleSearch = () => {
  ElMessage.info('搜索功能即将上线')
}

// 新建聊天
const handleNewChat = () => {
  router.push('/chat/new')
}

// 拨打电话
const handleCall = () => {
  if (currentConversation.value) {
    ElMessage.info(`正在连接通话...`)
  }
}

// 切换聊天菜单
const toggleChatMenu = () => {
  showChatMenu.value = !showChatMenu.value
  if (showChatMenu.value) {
    showProfileMenu.value = false
  }
}

// 切换个人资料菜单
const toggleProfileMenu = () => {
  showProfileMenu.value = !showProfileMenu.value
  if (showProfileMenu.value) {
    showChatMenu.value = false
  }
}

// 拉黑用户
const handleBlockUser = async () => {
  if (!currentConversation.value) return;

  try {
    await ElMessageBox.confirm(
      '确定要拉黑该用户吗？拉黑后该用户将无法向您发送消息，也无法购买您的商品。',
      '拉黑用户',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 调用拉黑API
    const response = await blockUser(currentConversation.value.partnerId);
    
    if (response.code === 200) {
      ElMessage.success('已成功拉黑该用户');
      // 可以选择关闭当前对话或返回会话列表
      router.push('/chat');
    } else {
      ElMessage.error(response.msg || '拉黑用户失败');
    }
  } catch (error) {
    // 用户取消操作或发生错误
    console.log('取消拉黑操作或发生错误:', error);
  }
};

// 查看更多商品
const viewAllProducts = () => {
  if (currentConversation.value) {
    router.push(`/user/products?userId=${currentConversation.value.partnerId}`)
  } else {
    router.push('/user/products')
  }
}

// 将reactive数组类型从interface改为ChatMessage
const messages = reactive<ChatMessage[]>([
    {
        id: 1,
    type: 'received',
    content: '你好，请问这台 MacBook Pro 卖在多少钱？',
    timestamp: '09:42'
            },
            {
                id: 2,
    type: 'sent',
    content: '',
    timestamp: '09:45',
    isProduct: true,
    product: {
      name: 'MacBook Pro 2018',
      price: '¥7000',
      image: 'https://api.dicebear.com/7.x/shapes/svg?seed=bridge&backgroundColor=2980b9'
    }
  },
  {
    id: 3,
    type: 'received',
    content: '太好了！能告诉我书的具体情况吗？有划痕或笔记吗？',
    timestamp: '09:47'
  },
  {
    id: 4,
    type: 'sent',
    content: '书的品相很好，几乎全新。我很爱惜书，所以没有笔记或划痕。',
    timestamp: '09:50'
  },
  {
    id: 5,
    type: 'received',
    content: '价格能优惠吗？',
    timestamp: '09:52'
  },
  {
    id: 6,
    type: 'sent',
    content: '如果你全部买下的话，可以优惠10%',
    timestamp: '09:55'
  },
  {
    id: 7,
    type: 'sent',
    content: '',
    timestamp: '09:56',
    isProduct: true,
    product: {
      name: '数据结构与算法分析（第3版）',
      price: '¥45.00',
      image: 'https://api.dicebear.com/7.x/icons/svg?seed=book'
    }
  },
  {
    id: 8,
    type: 'received',
    content: '好的，我都要！',
    timestamp: '10:00'
  }
])

// 阻止缩放的函数
const preventZoom = (e: WheelEvent | TouchEvent | KeyboardEvent) => {
  // 阻止ctrl+滚轮缩放
  if (e.type === 'wheel' && (e as WheelEvent).ctrlKey) {
    e.preventDefault();
  }
  
  // 阻止触摸缩放(双指触控)
  if (e.type === 'touchmove' && (e as TouchEvent).touches.length > 1) {
    e.preventDefault();
  }
  
  // 阻止键盘缩放 (Ctrl+加号/减号)
  if (e.type === 'keydown') {
    const keyEvent = e as KeyboardEvent;
    if (keyEvent.ctrlKey && (keyEvent.key === '+' || keyEvent.key === '-' || keyEvent.key === '=')) {
      e.preventDefault();
    }
  }
};

// 添加置顶/取消置顶的方法
const togglePinConversation = () => {
  if (!currentConversation.value) return;
  
  const conversationId = currentConversation.value.id;
  const index = pinnedConversations.value.indexOf(conversationId);
  
  if (index === -1) {
    // 添加到置顶
    pinnedConversations.value.push(conversationId);
    ElMessage.success('会话已置顶');
  } else {
    // 取消置顶
    pinnedConversations.value.splice(index, 1);
    ElMessage.success('已取消置顶');
  }
  
  // 保存到本地存储
  localStorage.setItem('pinnedConversations', JSON.stringify(pinnedConversations.value));
};

// 在组件挂载时添加meta标签和事件监听器
onMounted(() => {
  // 从本地存储加载置顶会话
  const savedPinnedConversations = localStorage.getItem('pinnedConversations');
  if (savedPinnedConversations) {
    try {
      pinnedConversations.value = JSON.parse(savedPinnedConversations);
    } catch (e) {
      console.error('解析置顶会话失败:', e);
    }
  }

  // 如果用户已登录，加载会话列表
  if (userStore.isLoggedIn) {
    fetchConversations().then(() => {
      // 加载会话列表后处理路由参数
      handleRouteParams();
    });
  }
  
  scrollToBottom();
  
  // 添加禁止缩放的相关逻辑
  const metaViewport = document.createElement('meta');
  metaViewport.name = 'viewport';
  metaViewport.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
  document.head.appendChild(metaViewport);
  
  document.addEventListener('wheel', preventZoom, { passive: false });
  document.addEventListener('touchmove', preventZoom, { passive: false });
  document.addEventListener('keydown', preventZoom, { passive: false });
  
  window.addEventListener('wheel', (e) => {
    if (e.ctrlKey) e.preventDefault();
  }, { passive: false });
  
  const style = document.createElement('style');
  style.id = 'anti-zoom-style';
  style.textContent = `
    html, body {
      touch-action: pan-x pan-y !important;
      -ms-content-zooming: none !important;
      -ms-touch-action: pan-x pan-y !important;
    }
  `;
  document.head.appendChild(style);

  // 请求通知权限
  notificationService.requestNotificationPermission();
  
  // 加载通知设置
  const settings = notificationService.getNotificationSettings();
  muteNotifications.value = settings.muteNotifications;
  muteSounds.value = settings.muteSounds;
  
  // 加载当前用户资料
  if (userStore.isLoggedIn && userStore.userInfo) {
    currentUserProfile.value = {
      id: userStore.userInfo.id,
      username: userStore.userInfo.username,
      nickname: userStore.userInfo.nickname,
      avatar: userStore.userInfo.avatar,
      school: '',
      phone: '',
      region: '',
      introduction: '',
      balance: 0,
      messageCount: 0,
      reputation: 0
    };
  }
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', scrollToBottom);
});

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', scrollToBottom);
});

// 在muteNotifications与muteSounds添加监听
watch(muteNotifications, (newValue) => {
  notificationService.updateNotificationSettings({ muteNotifications: newValue });
});

watch(muteSounds, (newValue) => {
  notificationService.updateNotificationSettings({ muteSounds: newValue });
});

// 监听会话变化，重新加载消息
watch(currentConversation, (newConversation) => {
  if (newConversation) {
    fetchMessages(newConversation.id);
    
    // 从会话对象中提取详细信息
    userProfile.value = {
      id: newConversation.partnerId,
      username: newConversation.partnerName,
      nickname: newConversation.partnerName,
      avatar: newConversation.partnerAvatar,
      school: newConversation.school,
      phone: newConversation.phone,
      region: newConversation.region,
      introduction: newConversation.introduction,
      messageCount: 0,
      balance: 0,
      reputation: 0
    };
    
    // 如果会话中包含商品信息，则显示商品数据
    if (newConversation.productId) {
      userProducts.value = [{
        id: newConversation.productId,
        title: newConversation.productTitle || '未知商品',
        price: 0,  // 价格信息可能需要从其他地方获取
        images: newConversation.productThumbnail ? [newConversation.productThumbnail] : []
      }];
      userProductsCount.value = 1;
    } else {
      userProducts.value = [];
      userProductsCount.value = 0;
    }
  }
});

// 监听消息变化，滚动到底部
watch(messages, () => {
    scrollToBottom();
}, { deep: true });

// 其他保留的功能和工具方法
// ...其余部分保持不变

// 获取会话列表
const fetchConversations = async () => {
  if (!userStore.isLoggedIn) return;
  
  try {
    loading.value = true;
    const response = await getChatConversations({ 
      userId: userStore.userInfo.id,
      page: 1,
      pageSize: 20
    });
    
    if (response.code === 200) {
      // 处理不同的数据结构情况
      if (response.data && Array.isArray(response.data)) {
        // 直接是数组的情况: { code: 200, data: [...] }
        // 遍历数据并确保字段正确映射
        conversations.value = response.data.map((conv: any) => ({
          id: conv.id,
          partnerId: conv.userId || conv.partnerId || (typeof conv.user === 'object' ? conv.user.id : null),
          partnerName: conv.username || conv.partnerName || (typeof conv.user === 'object' ? conv.user.username : null),
          partnerAvatar: conv.avatar || conv.partnerAvatar || (typeof conv.user === 'object' ? conv.user.avatar : null),
          lastMessage: typeof conv.lastMessage === 'object' ? conv.lastMessage : {
            content: typeof conv.lastMessage === 'string' ? conv.lastMessage : ''
          },
          unreadCount: typeof conv.unreadCount === 'number' ? conv.unreadCount : 0,
          updatedAt: conv.updatedAt || new Date().toISOString(),
          // 保存额外的字段信息
          school: conv.school,
          phone: conv.phone,
          region: conv.region,
          introduction: conv.introduction,
          productId: conv.productId,
          productTitle: conv.productTitle,
          productThumbnail: conv.productThumbnail
        }));
      } else if (response.data && response.data.content && Array.isArray(response.data.content)) {
        // 包含content字段的情况: { code: 200, data: { content: [...] } }
        conversations.value = response.data.content.map((conv: any) => ({
          id: conv.id,
          partnerId: conv.userId || conv.partnerId || (typeof conv.user === 'object' ? conv.user.id : null),
          partnerName: conv.username || conv.partnerName || (typeof conv.user === 'object' ? conv.user.username : null),
          partnerAvatar: conv.avatar || conv.partnerAvatar || (typeof conv.user === 'object' ? conv.user.avatar : null),
          lastMessage: typeof conv.lastMessage === 'object' ? conv.lastMessage : {
            content: typeof conv.lastMessage === 'string' ? conv.lastMessage : ''
          },
          unreadCount: typeof conv.unreadCount === 'number' ? conv.unreadCount : 0,
          updatedAt: conv.updatedAt || new Date().toISOString(),
          // 保存额外的字段信息
          school: conv.school,
          phone: conv.phone,
          region: conv.region,
          introduction: conv.introduction,
          productId: conv.productId,
          productTitle: conv.productTitle,
          productThumbnail: conv.productThumbnail
        }));
      } else {
        // 其他未预期的结构，尝试查找任何数组
        console.warn('未识别的会话数据结构:', response);
        // 使用模拟数据
        useMockConversations();
        ElMessage.warning('数据结构异常，使用模拟会话数据');
        return;
      }
      
      // 如果有会话并且没有选中的会话，自动选中第一个
      if (conversations.value.length > 0 && !currentConversation.value) {
        await selectConversation(conversations.value[0]);
      }
    } else {
      // 使用模拟数据
      useMockConversations();
      ElMessage.warning('使用模拟会话数据');
    }
  } catch (error) {
    console.error('获取会话列表失败:', error);
    // 使用模拟数据
    useMockConversations();
    ElMessage.warning('网络错误，使用模拟会话数据');
  } finally {
    loading.value = false;
  }
};

// 模拟会话数据
const useMockConversations = () => {
  conversations.value = [
    {
      id: 1,
      partnerId: 2,
      partnerName: '张三',
      partnerAvatar: 'https://api.dicebear.com/7.x/micah/svg?seed=user1',
      lastMessage: {
        id: 100,
        conversationId: 1,
        senderId: 2,
        receiverId: currentUserId.value,
        content: '价格能优惠吗？',
        type: 'text',
        createdAt: new Date().toISOString(),
        status: 'delivered'
      },
      unreadCount: 1,
      updatedAt: new Date().toISOString()
    },
    {
      id: 2,
      partnerId: 3,
      partnerName: '李四',
      partnerAvatar: 'https://api.dicebear.com/7.x/micah/svg?seed=user2',
      lastMessage: {
        id: 101,
        conversationId: 2,
        senderId: currentUserId.value,
        receiverId: 3,
        content: '商品还在吗？',
        type: 'text',
        createdAt: new Date(Date.now() - 3600000).toISOString(),
        status: 'read'
      },
      unreadCount: 0,
      updatedAt: new Date(Date.now() - 3600000).toISOString()
    }
  ];
  
  // 如果没有选中的会话，自动选中第一个
  if (conversations.value.length > 0 && !currentConversation.value) {
    selectConversation(conversations.value[0]);
  }
};

// 获取聊天记录
const fetchMessages = async (conversationId: number) => {
  if (!userStore.isLoggedIn || !userStore.userInfo) return; // 确保 userInfo 存在

  try {
    messagesLoading.value = true;
    const response = await getChatMessages({ 
      userId: userStore.userInfo.id, // 添加 userId
      conversationId,
      page: 1, // 添加必填的页码参数
      pageSize: 50 // 增加每页数量以获取更多历史消息
    });
    
    if (response.code === 200) {
      // 将API返回的消息转换为本地消息格式
      messages.splice(0, messages.length); // 清空现有消息
      
      // 处理不同的数据结构情况
      let messageItems: any[] = [];
      
      if (response.data && Array.isArray(response.data)) {
        // 直接是数组的情况: { code: 200, data: [...] }
        messageItems = response.data;
      } else if (response.data && response.data.content && Array.isArray(response.data.content)) {
        // 包含content字段的情况: { code: 200, data: { content: [...] } }
        messageItems = response.data.content;
      } else {
        // 其他未预期的结构，使用模拟数据
        console.warn('未识别的消息数据结构:', response);
        useMockMessages(conversationId);
        ElMessage.warning('消息数据结构异常，使用模拟消息数据');
        return;
      }
      
      // 按时间排序，确保旧消息在前，新消息在后
      messageItems.sort((a, b) => {
        let dateA: Date;
        let dateB: Date;
        
        if (Array.isArray(a.createdAt)) {
          dateA = new Date(
            a.createdAt[0],           // 年
            a.createdAt[1] - 1,       // 月（减1，因为JS中月份从0开始）
            a.createdAt[2],           // 日
            a.createdAt[3],           // 时
            a.createdAt[4],           // 分
            a.createdAt[5] || 0       // 秒（如果没有则默认为0）
          );
        } else {
          dateA = new Date(a.createdAt);
        }
        
        if (Array.isArray(b.createdAt)) {
          dateB = new Date(
            b.createdAt[0],           // 年
            b.createdAt[1] - 1,       // 月（减1，因为JS中月份从0开始）
            b.createdAt[2],           // 日
            b.createdAt[3],           // 时
            b.createdAt[4],           // 分
            b.createdAt[5] || 0       // 秒（如果没有则默认为0）
          );
        } else {
          dateB = new Date(b.createdAt);
        }
        
        return dateA.getTime() - dateB.getTime();
      });
      
      // 防止重复消息
      const uniqueMessageIds = new Set<number>();
      
      messageItems.forEach(msg => {
        // 跳过已添加的消息ID
        if (uniqueMessageIds.has(msg.id)) {
          return;
        }
        
        uniqueMessageIds.add(msg.id);
        
        // 判断是否为求购卡片消息
        const isPurchaseRequest = msg.purchaseRequestId != null && msg.purchaseRequestId !== 0;
        const isProductCard = msg.type === 'product' || msg.productId != null;
        
        // 构建基本消息对象
        const formattedMsg: ChatMessage = {
          id: msg.id,
          type: msg.senderId === currentUserId.value ? 'sent' : 'received',
          content: msg.content,
          timestamp: formatMessageTime(msg.createdAt),
          isProduct: isProductCard || isPurchaseRequest
        };
        
        // 如果是商品卡片
        if (isProductCard) {
          formattedMsg.product = {
            name: msg.productInfo?.title || msg.productInfo?.name || msg.productName || '商品',
            price: msg.productInfo?.price ? `¥${msg.productInfo.price}` : (msg.productPrice ? `¥${msg.productPrice}` : '¥暂无价格'),
            image: msg.productInfo?.image || msg.productInfo?.images?.[0] || msg.productImage || `https://api.dicebear.com/7.x/shapes/svg?seed=product${msg.productId}&backgroundColor=2980b9`,
            // 确保这些ID字段可以用于后续的处理
            ...(msg.productId ? { productId: msg.productId } : {})
          };
        } 
        // 如果是求购卡片
        else if (isPurchaseRequest) {
          formattedMsg.isPurchaseRequest = true;
          formattedMsg.product = {
            name: msg.purchaseRequestName || '求购商品',
            price: msg.purchaseRequestBudget ? `¥${msg.purchaseRequestBudget}` : '¥待议',
            image: 'https://api.dicebear.com/7.x/shapes/svg?seed=request&backgroundColor=FF8C00',
            purchaseRequestId: msg.purchaseRequestId,
            purchaseRequestName: msg.purchaseRequestName
          };
        }
        
        messages.push(formattedMsg);
      });
      
      await nextTick();
      scrollToBottom();
    } else {
      // 使用模拟消息数据
      useMockMessages(conversationId);
      ElMessage.warning('使用模拟消息数据');
    }
  } catch (error) {
    console.error('获取聊天记录失败:', error);
    // 使用模拟消息数据
    useMockMessages(conversationId);
    ElMessage.warning('网络错误，使用模拟消息数据');
  } finally {
    messagesLoading.value = false;
  }
};

// 模拟消息数据
const useMockMessages = (conversationId: number) => {
  messages.splice(0, messages.length); // 清空现有消息
  
  // 根据会话ID提供不同的模拟数据
  if (conversationId === 1) {
    messages.push(
      {
        id: 1,
        type: 'received',
        content: '你好，请问这台 MacBook Pro 卖在多少钱？',
        timestamp: formatTimeAgo(new Date(Date.now() - 3600000 * 2))
      },
      {
        id: 2,
        type: 'sent',
        content: '',
        timestamp: formatTimeAgo(new Date(Date.now() - 3600000 * 1.5)),
        isProduct: true,
        product: {
          name: 'MacBook Pro 2018',
          price: '¥7000',
          image: 'https://api.dicebear.com/7.x/shapes/svg?seed=bridge&backgroundColor=2980b9'
        }
      },
      {
        id: 3,
        type: 'received',
        content: '价格能优惠吗？',
        timestamp: formatTimeAgo(new Date(Date.now() - 3600000 * 0.5))
      }
    );
  } else {
    messages.push(
      {
        id: 4,
        type: 'sent',
        content: '商品还在吗？',
        timestamp: formatTimeAgo(new Date(Date.now() - 3600000 * 24))
      },
      {
        id: 5,
        type: 'received',
        content: '是的，还在的',
        timestamp: formatTimeAgo(new Date(Date.now() - 3600000 * 23))
      },
      {
        id: 6,
        type: 'sent',
        content: '我想了解一下具体情况',
        timestamp: formatTimeAgo(new Date(Date.now() - 3600000 * 22))
      }
    );
  }
  
  scrollToBottom();
};

// 格式化消息时间
const formatMessageTime = (timestamp: string | number[]) => {
  if (!timestamp) return '';
  
  let date: Date;
  
  // 处理数组格式的时间 [年, 月, 日, 时, 分, 秒]
  if (Array.isArray(timestamp)) {
    date = new Date(
      timestamp[0],           // 年
      timestamp[1] - 1,       // 月（减1，因为JS中月份从0开始）
      timestamp[2],           // 日
      timestamp[3],           // 时
      timestamp[4],           // 分
      timestamp[5] || 0       // 秒（如果没有则默认为0）
    );
  } else {
    date = new Date(timestamp);
  }
  
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
};

// 格式化相对时间
const formatTimeAgo = (dateInput: Date | number[]) => {
  let date: Date;
  
  // 处理数组格式的时间 [年, 月, 日, 时, 分, 秒]
  if (Array.isArray(dateInput)) {
    // 注意：JavaScript中月份是从0开始的，所以需要将月份值减1
    date = new Date(
      dateInput[0], // 年
      dateInput[1] - 1, // 月（减1，因为JS中月份从0开始）
      dateInput[2], // 日
      dateInput[3], // 时
      dateInput[4], // 分
      dateInput[5]  // 秒
    );
  } else {
    date = dateInput;
  }
  
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffHours = diffMs / (1000 * 60 * 60);
  
  if (diffHours < 24) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  } else {
    return date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' }) + ' ' + 
           date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
};

// 滚动到消息底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      // 使用更可靠的方式强制滚动到底部
      setTimeout(() => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
      }, 50);
    }
  });
};

// 选择会话
const selectConversation = async (conversation: ChatConversation) => {
  currentConversation.value = conversation;
  await fetchMessages(conversation.id);
  
  // 标记为已读
  if (conversation.unreadCount > 0) {
    await markConversationAsRead({ 
      userId: userStore.userInfo.id, 
      conversationId: conversation.id 
    });
    // 更新本地会话的未读数
    conversation.unreadCount = 0;
  }
};

// 发送消息
const sendMessage = async (message?: string, productId?: number, requestId?: number) => {
  if (!currentConversation.value || !userStore.userInfo) return;
  
  console.log("sendMessage函数被调用 - 参数:", { message, productId, requestId });
  
  // 如果是发送商品或求购卡片，可以设置为空消息
  const messageText = message || messageInput.value.trim();
  if (!messageText && !productId && !requestId) {
    if (!message) ElMessage.warning('消息不能为空');
    return;
  }
  
  try {
    const requestData: any = {
      userId: userStore.userInfo.id,
      receiverId: currentConversation.value.partnerId,
      conversationId: currentConversation.value.id,
      content: messageText || ' '  // 确保content不为空
    };
    
    // 如果有商品ID或求购ID，添加到请求体中
    if (productId) {
      requestData.productId = productId;
      console.log("准备发送商品卡片:", requestData);
    }
    
    if (requestId) {
      requestData.requestId = requestId;
      console.log("准备发送求购卡片:", requestData);
    }
    
    console.log("发送消息请求数据:", requestData);
    const response = await sendChatMessage(requestData);
    console.log("发送消息响应:", response);
    
    if (response.code === 200) {
      // 清空输入框
      if (!message) messageInput.value = ''; // 只有当不是外部提供的消息时才清空输入框
      
      // 检查消息是否已存在（防止重复）
      const existingMessageIndex = messages.findIndex(m => m.id === response.data.id);
      if (existingMessageIndex >= 0) {
        // 已存在该消息，不再添加
        return;
      }

      // 添加发送的消息到本地消息列表
  const newMessage: ChatMessage = {
        id: response.data.id,
        type: 'sent',
        content: messageText,
        timestamp: formatMessageTime(response.data.createdAt),
        isNew: true,
        isProduct: productId ? true : (requestId ? true : false),
        product: (productId || requestId) && response.data.productInfo ? {
          name: response.data.productInfo.title || response.data.productInfo.name || (requestId ? '求购商品' : '商品'),
          price: response.data.productInfo.price ? `¥${response.data.productInfo.price}` : 
                 (requestId && response.data.productInfo.purchaseRequestBudget ? `¥${response.data.productInfo.purchaseRequestBudget}` : '¥待议'),
          image: response.data.productInfo.image || response.data.productInfo.images?.[0] || 
                 (requestId ? 'https://api.dicebear.com/7.x/shapes/svg?seed=request&backgroundColor=FF8C00' : '')
        } : undefined
  };
  
  messages.push(newMessage);

      // 更新当前会话的最后一条消息
      if (currentConversation.value) {
        currentConversation.value.lastMessage = response.data;
        currentConversation.value.updatedAt = response.data.createdAt;
      }
      
      await nextTick();
      scrollToBottom();
      
      // 100ms 后移除新消息标记
  setTimeout(() => {
        newMessage.isNew = false;
      }, 100);
      
      return response.data;  // 返回发送结果，方便调用方确认状态
    } else {
      console.error("发送消息失败:", response);
      ElMessage.error(response.message || '发送失败');
      
      // 使用模拟发送消息
      if (productId) {
        sendMockProductCard(productId);
      } else if (requestId) {
        sendMockRequestCard(requestId);
      } else {
        sendMockMessage(messageText);
      }
      ElMessage.warning('使用模拟发送消息');
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    // 使用模拟发送消息
    if (productId) {
      sendMockProductCard(productId);
    } else if (requestId) {
      sendMockRequestCard(requestId);
    } else {
      sendMockMessage(messageText);
    }
    ElMessage.warning('网络错误，使用模拟发送消息');
  }
};

// 修改模拟发送消息逻辑，增加通知功能
// 模拟发送消息
const sendMockMessage = (message?: string) => {
  const messageText = message || messageInput.value.trim();
  if (!message) messageInput.value = ''; // 只有当不是外部提供的消息时才清空输入框
  
  // 生成唯一ID
  const msgId = Date.now();
  
  // 检查是否已有相同内容的消息（防止重复）
  if (messages.some(m => m.type === 'sent' && m.content === messageText)) {
    return;
  }
  
  // 创建模拟消息
  const newMessage: ChatMessage = {
    id: msgId,
    type: 'sent',
    content: messageText,
    timestamp: formatMessageTime(new Date().toISOString()),
    isNew: true
  };
  
  messages.push(newMessage);
  
  // 更新当前会话的最后一条消息
  if (currentConversation.value) {
    currentConversation.value.lastMessage = {
      id: newMessage.id,
      conversationId: currentConversation.value.id,
      senderId: currentUserId.value,
      receiverId: currentConversation.value.partnerId,
      content: messageText,
      type: 'text',
      createdAt: new Date().toISOString(),
      status: 'sent'
    };
    currentConversation.value.updatedAt = new Date().toISOString();
  }
  
  scrollToBottom();
    
  // 100ms 后移除新消息标记
  setTimeout(() => {
    newMessage.isNew = false;
  }, 100);
  
  // 模拟收到回复 (2秒后)
  setTimeout(() => {
    if (currentConversation.value) {
      // 生成不同的ID
      const replyMsgId = Date.now() + 1;
      
      const replyMessage: ChatMessage = {
        id: replyMsgId,
        type: 'received',
        content: '这是一条模拟自动回复消息',
        timestamp: formatMessageTime(new Date().toISOString()),
        isNew: true
      };
      
      messages.push(replyMessage);
      
      // 更新当前会话的最后一条消息
      currentConversation.value.lastMessage = {
        id: replyMessage.id,
        conversationId: currentConversation.value.id,
        senderId: currentConversation.value.partnerId,
        receiverId: currentUserId.value,
        content: replyMessage.content,
        type: 'text',
        createdAt: new Date().toISOString(),
        status: 'delivered'
      };
      currentConversation.value.updatedAt = new Date().toISOString();
      currentConversation.value.unreadCount++;
      
      scrollToBottom();
      
      // 100ms 后移除新消息标记
      setTimeout(() => {
        replyMessage.isNew = false;
      }, 100);

      // 如果当前不在聊天页面，显示通知
      if (document.hidden || document.visibilityState === 'hidden') {
        notificationService.showChatNotification(
          currentConversation.value.partnerName, 
          replyMessage.content,
          currentConversation.value.partnerAvatar
        );
      }
    }
  }, 2000);
};

// 删除当前会话
const deleteCurrentConversation = async () => {
  if (!currentConversation.value || !userStore.userInfo) return; // 确保 userInfo 和 conversation 存在
  
  try {
    await ElMessageBox.confirm('确定要删除此会话吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await deleteConversation({
      userId: userStore.userInfo.id, // 添加 userId
      conversationId: currentConversation.value.id
    });
    
    if (response.code === 200) {
      conversations.value = conversations.value.filter(c => c.id !== currentConversation.value?.id);
      currentConversation.value = null;
      messages.splice(0, messages.length); // 清空消息
      ElMessage.success('会话已删除');
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会话失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

// 处理路由参数并建立对话
const handleRouteParams = async () => {
  if (!userStore.isLoggedIn || !userStore.userInfo) return;
  
  const sellerId = Number(route.query.sellerId);
  const productId = Number(route.query.productId);
  const requestId = Number(route.query.requestId);
  
  console.log("handleRouteParams - 参数:", { sellerId, productId, requestId });
  
  // 如果没有需要处理的参数，直接返回
  if (!sellerId) return;
  
  try {
    // 查找是否已有与该卖家的会话
    let targetConversation = conversations.value.find(conv => conv.partnerId === sellerId);
    console.log("现有会话:", targetConversation);
    
    // 如果没有现有会话，创建新会话
    if (!targetConversation) {
      loading.value = true;
      console.log("创建新会话...");
      const response = await createConversation({
        userId: userStore.userInfo.id,
        partnerId: sellerId
      });
      
      if (response.code === 200) {
        // 新创建的会话
        targetConversation = response.data;
        conversations.value.unshift(targetConversation);
        console.log("会话创建成功:", targetConversation);
      } else {
        console.error("创建会话失败:", response);
        ElMessage.error('创建会话失败');
        return;
      }
    }
    
    // 选择会话
    await selectConversation(targetConversation);
    console.log("已选择会话:", currentConversation.value);
    
    // 首先确认会话已加载
    if (!currentConversation.value) {
      console.error("当前会话未加载，无法发送卡片");
      ElMessage.error('会话加载失败，请刷新页面重试');
      return;
    }
    
    // 如果有商品ID，发送商品卡片
    if (productId) {
      // 检查是否已经发送过该商品卡片（使用会话ID和商品ID组合作为标识）
      const sentProductKey = `sent_product_${currentConversation.value.id}_${productId}`;
      const hasBeenSent = sessionStorage.getItem(sentProductKey);
      
      // 如果没有发送过，则发送商品卡片
      if (!hasBeenSent) {
        console.log("准备发送商品卡片, productId:", productId);
        try {
          // 使用统一的sendMessage函数发送商品卡片
          const result = await sendMessage('', productId);
          console.log("商品卡片发送结果:", result);
          
          if (result) {
            // 记录已发送状态
            sessionStorage.setItem(sentProductKey, 'true');
          } else {
            console.error("商品卡片发送失败");
            // 使用模拟数据发送卡片
            sendMockProductCard(productId);
            // 记录已发送状态
            sessionStorage.setItem(sentProductKey, 'true');
          }
        } catch (error) {
          console.error('发送商品卡片失败:', error);
          // 使用模拟数据发送卡片
          sendMockProductCard(productId);
          // 记录已发送状态（即使用的是模拟数据，也记录为已发送）
          sessionStorage.setItem(sentProductKey, 'true');
        }
      } else {
        console.log("商品卡片已发送过，不再重复发送");
      }
    }
    
    // 如果有求购ID，发送求购卡片
    if (requestId) {
      // 检查是否已经发送过该求购卡片（使用会话ID和求购ID组合作为标识）
      const sentRequestKey = `sent_request_${currentConversation.value.id}_${requestId}`;
      const hasBeenSent = sessionStorage.getItem(sentRequestKey);
      
      // 如果没有发送过，则发送求购卡片
      if (!hasBeenSent) {
        console.log("准备发送求购卡片, requestId:", requestId);
        try {
          // 直接发送求购卡片
          const result = await sendMessage('', undefined, requestId);
          console.log("求购卡片发送结果:", result);
          
          if (result) {
            // 发送一条询问消息
            const initialMessage = `您好，我想咨询一下您发布的求购信息。`;
            await sendMessage(initialMessage);
            // 记录已发送状态
            sessionStorage.setItem(sentRequestKey, 'true');
          } else {
            console.error("求购卡片发送失败");
            // 如果发送失败，使用模拟数据
            sendMockRequestCard(requestId);
            const initialMessage = '您好，我想咨询一下您发布的求购信息。';
            await sendMessage(initialMessage);
            // 记录已发送状态
            sessionStorage.setItem(sentRequestKey, 'true');
          }
        } catch (error) {
          console.error('发送求购卡片失败:', error);
          // 使用模拟数据发送卡片
          sendMockRequestCard(requestId);
          const initialMessage = '您好，我想咨询一下您发布的求购信息。';
          await sendMessage(initialMessage);
          // 记录已发送状态
          sessionStorage.setItem(sentRequestKey, 'true');
        }
      } else {
        console.log("求购卡片已发送过，不再重复发送");
      }
    }
  } catch (error) {
    console.error('处理路由参数失败:', error);
    ElMessage.error('连接聊天失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 模拟发送商品卡片
const sendMockProductCard = (productId: number) => {
  const newMessage: ChatMessage = {
    id: Date.now(),
    type: 'sent',
    content: '',
    timestamp: formatMessageTime(new Date().toISOString()),
    isProduct: true,
    product: {
      name: '求购商品',
      price: '¥待议',
      image: 'https://api.dicebear.com/7.x/shapes/svg?seed=product&backgroundColor=2980b9'
    },
    isNew: true
  };
  
  messages.push(newMessage);
  
  // 更新当前会话的最后一条消息
  if (currentConversation.value) {
    currentConversation.value.lastMessage = {
      id: newMessage.id,
      conversationId: currentConversation.value.id,
      senderId: currentUserId.value,
      receiverId: currentConversation.value.partnerId,
      content: '发送了一个商品',
      type: 'product',
      createdAt: new Date().toISOString(),
      status: 'sent'
    };
    currentConversation.value.updatedAt = new Date().toISOString();
  }
  
  nextTick(() => {
    scrollToBottom();
  });
  
  // 100ms 后移除新消息标记
  setTimeout(() => {
    if (newMessage.isNew !== undefined) {
      newMessage.isNew = false;
    }
  }, 100);
};

// 用户名缓存
const userNames = ref<Record<number, string>>({})

// 根据用户ID获取默认头像
const getDefaultAvatar = (userId: number) => {
  // 首先尝试检查用户是否上传了头像文件
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    try {
      const parsedUserInfo = JSON.parse(userInfo);
      // 如果是当前用户，并且有头像信息
      if (parsedUserInfo.id === userId && parsedUserInfo.avatar) {
        // 检查是否是完整的URL
        if (parsedUserInfo.avatar.startsWith('http')) {
          return parsedUserInfo.avatar;
        }
        // 检查是否是@user目录下的文件
        return `/images/user/${parsedUserInfo.avatar}`;
      }
    } catch (err) {
      console.error('解析用户信息失败:', err);
    }
  }
  
  // 如果没有找到头像信息，使用生成的头像
  return `https://api.dicebear.com/7.x/initials/svg?seed=${userId}&backgroundColor=007AFF&fontColor=ffffff`;
}


// 格式化消息内容，如果是JSON字符串则提取出实际消息内容
const formatMessageContent = (content: string) => {
  if (!content) return '';
  
  // 检查是否可能是JSON格式字符串
  if (content.startsWith('{') && content.includes(':')) {
    try {
      // 尝试解析JSON
      const jsonObj = JSON.parse(content);
      
      // 优先使用message字段
      if (jsonObj.message) {
        return jsonObj.message;
      }
      
      // 尝试使用content字段
      if (jsonObj.content) {
        return jsonObj.content;
      }
      
      // 尝试使用text字段
      if (jsonObj.text) {
        return jsonObj.text;
      }
      
      // 如果没有找到任何有效的内容字段但有其他字段，将对象转换为字符串
      if (Object.keys(jsonObj).length > 0) {
        // 尝试一些可能包含消息内容的字段
        for (const key of Object.keys(jsonObj)) {
          if (typeof jsonObj[key] === 'string' && jsonObj[key].length > 0) {
            return jsonObj[key];
          }
        }
        return JSON.stringify(jsonObj, null, 2);
      }
      
      // 如果所有尝试都失败，返回原始内容
      return content;
    } catch (error) {
      // 解析失败则返回原始内容
      console.error('消息格式解析失败:', error);
      return content;
    }
  }
  
  return content;
};

// 添加用户资料数据
const currentUserProfile = ref<UserProfile | null>(null)
const userProfile = ref<UserProfile | null>(null)
const userProductsCount = ref(0)
const userProducts = ref<Array<any>>([])
const userProfileLoading = ref(false)

// 添加模拟发送求购卡片的函数
const sendMockRequestCard = (requestId: number) => {
  const newMessage: ChatMessage = {
    id: Date.now(),
    type: 'sent',
    content: '',
    timestamp: formatMessageTime(new Date().toISOString()),
    isProduct: true,
    isPurchaseRequest: true,  // 添加这个标记
    product: {
      name: '求购商品',
      price: '¥待议',
      image: 'https://api.dicebear.com/7.x/shapes/svg?seed=request&backgroundColor=FF8C00',
      purchaseRequestId: requestId  // 添加请求ID
    },
    isNew: true
  };
  
  messages.push(newMessage);
  
  // 更新当前会话的最后一条消息
  if (currentConversation.value) {
    currentConversation.value.lastMessage = {
      id: newMessage.id,
      conversationId: currentConversation.value.id,
      senderId: currentUserId.value,
      receiverId: currentConversation.value.partnerId,
      content: '发送了一个求购卡片',
      type: 'product',
      createdAt: new Date().toISOString(),
      status: 'sent'
    };
    currentConversation.value.updatedAt = new Date().toISOString();
  }
  
  nextTick(() => {
    scrollToBottom();
  });
  
  // 100ms 后移除新消息标记
  setTimeout(() => {
    if (newMessage.isNew !== undefined) {
      newMessage.isNew = false;
    }
  }, 100);
};

// 添加跳转到求购详情的方法
const goToPurchaseRequestDetail = (product: any) => {
  if (product && product.purchaseRequestId) {
    router.push(`/request/detail?id=${product.purchaseRequestId}`);
  }
}

</script>

<style scoped>
/* 限制页面缩放的样式 */
.chat-container {
  min-width: 900px;
  max-width: 1800px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  overflow: hidden;
  touch-action: none; /* 禁止所有触摸操作 */
}

/* 禁止用户选择文本，避免双击缩放 */
* {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
  touch-action: pan-x pan-y; /* 只允许平移，不允许缩放 */
}

/* 允许输入区域选择文本 */
input, textarea {
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

/* 整体容器 */
.light-chat-container {
    height: calc(100vh - 70px);
    display: flex;
    background-color: #FFFFFF;
    font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
    font-weight: 500; /* 增加基础字体粗细 */
    font-size: 16px; /* 增加基础字体大小 */
    overflow: hidden;
    position: fixed;
    top: 70px; /* 为顶部导航栏留出更多空间 */
    left: 0;
    right: 0;
    bottom: 0;
    margin: 0;
    padding: 0;
    z-index: 100;
    width: 100%; /* 改为100%而不是100vw，避免产生滚动条 */
}

/* 中间聊天列表 - 设置为3份 */
.chat-list {
    width: 0;
    flex-basis: 0;
    flex-grow: 3;
    background-color: #F8FAFC;
    border-right: 1px solid #E2E8F0;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    position: relative;
    z-index: 3;
}

.chat-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 32px;
    border-bottom: 1px solid #E2E8F0;
    background-color: rgba(248, 250, 252, 0.95);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    z-index: 10;
    position: sticky;
    top: 0;
    transition: box-shadow 0.3s ease;
}

.chat-list-header.scrolled {
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.chat-list-header h1 {
    font-size: 28px; /* 增大标题字体 */
    font-weight: 700;
    color: #000000;
    margin: 0;
    letter-spacing: -0.5px;
}

.header-actions {
    display: flex;
    gap: 16px;
}

.icon-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 0;
    transition: transform 0.2s ease, opacity 0.2s ease;
}

.icon-btn:hover {
    transform: translateY(-1px);
    opacity: 0.8;
}

.chat-filters {
    display: flex;
    justify-content: space-between;
    padding: 12px 20px;
    background-color: rgba(255, 255, 255, 0.8);
    border-bottom: 1px solid rgba(229, 229, 234, 0.6);
    z-index: 9;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.01);
}

.filter-btn {
    padding: 8px 16px;
    border: none;
    border-radius: 10px;
    background-color: #F2F2F7;
    color: #000000;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.filter-btn:hover {
    background-color: #E9E9F0;
    transform: translateY(-1px);
    box-shadow: 0 3px 5px rgba(0, 0, 0, 0.08);
}

.filter-btn.active {
    background-color: #222222;
    color: #FFFFFF;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.pinned-section {
    padding: 12px 20px;
    border-bottom: 1px solid rgba(229, 229, 234, 0.6);
    background-color: rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    z-index: 8;
}

.pinned-label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    font-weight: 500;
    color: #8E8E93;
}

.chat-list-content {
    flex: 1;
    overflow-y: auto;
    overscroll-behavior: contain;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0.5), rgba(248, 249, 250, 0.8));
}

.chat-divider {
    padding: 12px 32px;
    font-size: 13px;
    font-weight: 600;
    letter-spacing: 0.2px;
    color: #8B5CF6;
    border-bottom: 1px solid rgba(229, 229, 234, 0.5);
    background-color: rgba(249, 245, 255, 0.97);
    position: sticky;
    top: 0;
    z-index: 2;
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
}

.chat-divider::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 32px;
    right: 32px;
    height: 1px;
    background: linear-gradient(90deg, 
        rgba(224, 231, 255, 0) 0%,
        #E0E7FF 50%,
        rgba(224, 231, 255, 0) 100%
    );
}

.chat-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px 32px;
    cursor: pointer;
    transition: all 0.25s ease;
    border-bottom: 1px solid #EDF2F7;
    background-color: transparent;
    position: relative;
}

.chat-item:hover {
    background-color: #F1F5F9;
    transform: translateX(2px);
}

.chat-item.active {
    background-color: rgba(124, 58, 237, 0.06);
    border-left: 3px solid #7C3AED;
    padding-left: 29px;
}

.chat-item:last-child {
    border-bottom: none;
}

.chat-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    flex-shrink: 0;
    position: relative;
    box-shadow: 0 0 0 2px #FFFFFF, 0 0 0 4px rgba(124, 58, 237, 0.15);
}

.chat-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.chat-info {
    flex: 1;
    min-width: 0;
}

.chat-name-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
}

.chat-name {
    font-size: 17px; /* 增大用户名字体 */
    font-weight: 600;
    color: #1F2937;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.chat-time {
    font-size: 14px; /* 增大列表时间字体 */
    color: rgba(142, 142, 147, 0.8);
    flex-shrink: 0;
    font-weight: 500;
}

.chat-preview {
    font-size: 16px; /* 增大预览字体 */
    color: rgba(142, 142, 147, 0.65);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-weight: 500;
}

.chat-badge {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 600;
    color: white;
    flex-shrink: 0;
    background-color: #8E8E93;
    box-shadow: inset 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.chat-badge.purple {
    background-color: #8B5CF6;
}

.chat-badge.unread {
    background-color: #EF4444;
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.9), 0 2px 4px rgba(239, 68, 68, 0.4);
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% {
        box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4), 0 0 0 2px rgba(255, 255, 255, 0.9);
    }
    70% {
        box-shadow: 0 0 0 6px rgba(239, 68, 68, 0), 0 0 0 2px rgba(255, 255, 255, 0.9);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(239, 68, 68, 0), 0 0 0 2px rgba(255, 255, 255, 0.9);
    }
}

.status-icon {
    flex-shrink: 0;
    color: #007AFF;
    font-size: 12px;
}

.status-icon.opacity {
    color: #8E8E93;
}

/* 中间聊天内容区域 - 设置为7份 */
.chat-detail {
    width: 0;
    flex-basis: 0;
    flex-grow: 7;
    display: flex;
    flex-direction: column;
    background: #FFFFFF;
    height: 100%;
    overflow: hidden;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.03), -2px 0 8px rgba(0, 0, 0, 0.03);
    position: relative;
    z-index: 2;
}

.chat-detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #E2E8F0;
    background-color: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    z-index: 5;
    position: sticky;
    top: 0;
    transition: box-shadow 0.3s ease;
}

.chat-detail-header.scrolled {
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header-left {
    display: flex;
    align-items: center;
}

.user-info {
    display: flex;
    align-items: center;
}

.user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    overflow: hidden;
    flex-shrink: 0;
    margin-right: 12px;
}

.user-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.user-name-container {
    display: flex;
    flex-direction: column;
}

.user-name {
    font-size: 18px; /* 增大聊天室标题字体 */
    font-weight: 600;
    color: #000000;
}

.user-status {
    font-size: 14px; /* 增大用户状态字体 */
    color: #8E8E93;
    margin-top: 0px;
    font-weight: 500;
}

.header-actions {
    display: flex;
    gap: 14px;
}

.icon-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.call-btn {
    width: 28px;
    height: 28px;
    background-color: #5E30EB;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.menu-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.messages-container {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    height: calc(100% - 120px);
    overscroll-behavior: contain;
    background: #FFFFFF;
    position: relative;
}

.date-separator {
    text-align: center;
    margin: 24px 0;
    position: relative;
}

.date-separator::before, .date-separator::after {
    content: '';
    position: absolute;
    top: 50%;
    width: calc(50% - 50px);
    height: 1px;
    background: linear-gradient(90deg, 
        rgba(224, 231, 255, 0) 0%,
        #E0E7FF 50%,
        rgba(224, 231, 255, 0) 100%
    );
}

.date-separator::before {
    left: 0;
    background: linear-gradient(90deg, 
        rgba(224, 231, 255, 0) 0%,
        #E0E7FF 100%
    );
}

.date-separator::after {
    right: 0;
    background: linear-gradient(90deg, 
        #E0E7FF 0%,
        rgba(224, 231, 255, 0) 100%
    );
}

.date-separator span {
    font-size: 15px; /* 增大日期分隔线字体 */
    font-weight: 600; /* 加粗日期分隔线字体 */
    color: #6366F1;
    padding: 4px 12px;
    background-color: rgba(224, 231, 255, 0.4);
    border-radius: 10px;
    position: relative;
    box-shadow: 0 1px 2px rgba(99, 102, 241, 0.1);
}

.message-row {
    display: flex;
    margin-bottom: 24px;
    align-items: flex-start;
    position: relative;
    width: 100%;
    animation: fadeIn 0.5s ease;
    transition: all 0.3s ease;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.message-row.sent-row {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
}

.message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    margin-top: 8px;
    flex-shrink: 0;
    position: relative;
    box-shadow: 0 0 0 2px #FFFFFF, 0 0 0 4px rgba(124, 58, 237, 0.15);
}

.message-row.sent-row .message-avatar {
    margin-left: 16px;
    order: 2;
}

.message-row:not(.sent-row) .message-avatar {
    margin-right: 16px;
    order: 1;
}

.message-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.message-column {
    display: flex;
    flex-direction: column;
    max-width: 70%;
}

.message-row.sent-row .message-column {
    order: 1;
    align-items: flex-end;
}

.message-row:not(.sent-row) .message-column {
    order: 2;
    align-items: flex-start;
}

.message-column.align-right {
    align-items: flex-end;
}

.message-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
    color: rgba(142, 142, 147, 0.65);
}

.sender-name {
    font-weight: 600;
    font-size: 16px; /* 增大发送者姓名字体 */
    margin-right: 8px;
    color: #1F2937;
}

.message-time {
    font-weight: 500;
    font-size: 14px; /* 增大时间字体 */
    margin: 0 8px;
    color: rgba(142, 142, 147, 0.65);
}

.message-bubble {
    padding: 12px 16px;
    border-radius: 18px;
    font-size: 17px; /* 增大消息气泡字体 */
    font-weight: 500; /* 加粗消息气泡字体 */
    line-height: 1.4;
    margin-bottom: 8px;
    max-width: 85%;
    position: relative;
    word-break: break-word;
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    min-height: 24px; /* 设置最小高度 */
}

.message-bubble:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.message-bubble::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    border-radius: inherit;
    z-index: -1;
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0);
    opacity: 0;
    transition: all 0.3s ease;
}

.message-bubble:hover::after {
    opacity: 1;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.message-bubble.received {
    background-color: rgba(240, 240, 240, 0.9);
    color: #1F2937;
    border-top-left-radius: 4px;
    align-self: flex-start;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(200, 200, 200, 0.3);
}

.message-bubble.sent {
    background-color: rgba(124, 58, 237, 0.1);
    color: #1F2937;
    border-top-right-radius: 4px;
    align-self: flex-end;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(124, 58, 237, 0.2);
}

.message-image {
    max-width: 240px;
    margin: 8px 0;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

.message-image:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.12);
}

.message-image img {
    width: 100%;
    height: auto;
    display: block;
    object-fit: cover;
    transition: transform 0.4s ease;
}

.message-image:hover img {
    transform: scale(1.05);
}

.message-input-area {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border-top: 1px solid rgba(229, 229, 234, 0.6);
    background-color: rgba(242, 242, 247, 0.9);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    z-index: 10;
    position: sticky;
    bottom: 0;
    gap: 10px;
    transition: all 0.3s ease;
    box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.03);
}

.message-input-area:focus-within {
    background-color: rgba(255, 255, 255, 0.95);
    box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.05);
}

.input-icon-btn {
    width: 36px;
    height: 36px;
    background: none;
    border: none;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;
    color: #007AFF;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.input-icon-btn::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 122, 255, 0.1);
    border-radius: 50%;
    transform: scale(0);
    transition: transform 0.3s ease;
}

.input-icon-btn:hover {
    transform: translateY(-2px);
}

.input-icon-btn:hover::before {
    transform: scale(1);
}

.input-icon-btn:active {
    transform: scale(0.9);
}

.input-icon-btn svg {
    position: relative;
    z-index: 1;
    transition: transform 0.3s ease;
}

.input-icon-btn:hover svg {
    transform: scale(1.1);
}

.message-input-container {
    flex: 1;
    position: relative;
    background-color: #FFFFFF;
    border-radius: 24px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

.message-input-container:focus-within {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-1px);
    border-color: rgba(151, 117, 250, 0.3);
}

.message-input {
    flex: 1;
    height: 40px;
    padding: 0 8px;
    border: none;
    border-radius: 18px;
    background-color: transparent;
    font-size: 17px; /* 增大输入框字体 */
    font-weight: 500; /* 加粗输入框字体 */
    outline: none;
    color: #000;
    font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Helvetica Neue', sans-serif;
    transition: transform 0.2s ease;
}

.message-input::placeholder {
    color: #AEAEB2;
    transition: color 0.3s ease, transform 0.3s ease;
}

.message-input:focus::placeholder {
    color: #C7C7CC;
    transform: translateX(5px);
}

/* 表情面板 */
.emoji-panel {
    padding: 24px 16px;
    background-color: rgba(255, 255, 255, 0.97);
    border-top: 1px solid #E2E8F0;
    max-height: 220px;
    overflow-y: auto;
    backdrop-filter: blur(15px);
    -webkit-backdrop-filter: blur(15px);
    box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.08);
    transform-origin: bottom;
    animation: slideUp 0.3s ease;
    z-index: 9;
    border-radius: 24px 24px 0 0;
    margin: 0 8px;
}

@keyframes slideUp {
    from { transform: translateY(30px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.emoji-grid {
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    gap: 16px;
}

.emoji-item {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    font-size: 28px;
    cursor: pointer;
    border-radius: 12px;
    transition: all 0.2s ease;
    background-color: #F8FAFC;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.04);
}

.emoji-item:hover {
    transform: scale(1.15) translateY(-3px);
    background-color: white;
    box-shadow: 0 5px 15px rgba(124, 58, 237, 0.2);
}

.emoji-item:active {
    transform: scale(0.95);
}

/* 功能面板样式 */
.feature-panel {
    padding: 32px 24px;
    background-color: rgba(255, 255, 255, 0.97);
    border-top: 1px solid #E2E8F0;
    backdrop-filter: blur(15px);
    -webkit-backdrop-filter: blur(15px);
    box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.08);
    transform-origin: bottom;
    animation: slideUp 0.3s ease;
    z-index: 9;
    border-radius: 24px 24px 0 0;
    margin: 0 8px;
}

.feature-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24px;
    margin-bottom: 32px;
}

.feature-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    transition: transform 0.3s ease;
    cursor: pointer;
}

.feature-item:hover {
    transform: translateY(-5px);
}

.feature-icon {
    width: 64px;
    height: 64px;
    border-radius: 20px;
    background: linear-gradient(145deg, #FFFFFF, #F8FAFC);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.feature-icon::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, rgba(124, 58, 237, 0.1), rgba(99, 102, 241, 0.1));
    opacity: 0;
    transition: opacity 0.3s ease;
}

.feature-item:hover .feature-icon {
    box-shadow: 0 8px 20px rgba(124, 58, 237, 0.15);
    transform: scale(1.05);
}

.feature-item:hover .feature-icon::before {
    opacity: 1;
}

.feature-icon svg {
    transition: transform 0.3s ease;
    z-index: 1;
    position: relative;
    stroke: #7C3AED;
}

.feature-item:hover .feature-icon svg {
    transform: scale(1.1);
}

.feature-item span {
    font-size: 16px; /* 增大功能按钮字体 */
    color: #1F2937;
    font-weight: 500;
    font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
    transition: color 0.3s ease;
    letter-spacing: 0.2px;
}

.feature-item:hover span {
    color: #7C3AED;
}

/* 输入区域调整 */
.feature-toggle-btn {
    position: relative;
    transition: all 0.3s ease;
}

.feature-toggle-btn.active {
    background-color: rgba(151, 117, 250, 0.15);
    transform: rotate(45deg);
}

.feature-toggle-btn.active svg {
    stroke: #9775FA;
}

.emoji-btn {
    margin-right: 5px;
}

.emoji-btn:focus, .emoji-btn.active {
    background-color: rgba(151, 117, 250, 0.15);
}

.emoji-btn.active svg {
    stroke: #9775FA;
}

/* 右侧个人资料栏 - 设置为4份 */
.profile-sidebar {
    width: 0;
    flex-basis: 0;
    flex-grow: 4;
    background: #F3F8FF;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    position: relative;
    z-index: 1;
    border-left: 1px solid #D0E1FF;
}

.profile-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #D0E1FF;
    background-color: #FFFFFF;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    z-index: 5;
    position: sticky;
    top: 0;
}

.profile-header h2 {
    font-size: 20px; /* 增大个人资料标题字体 */
    font-weight: 600;
    color: #0055FF;
    margin: 0;
    text-align: center;
    flex: 1;
}

.profile-content {
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow-y: auto;
    background: #F3F8FF;
}

.profile-info {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
    background-color: #FFFFFF;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 85, 255, 0.08);
}

.profile-info-header {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.profile-avatar-img {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    margin-bottom: 16px;
    object-fit: cover;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 3px solid #FFFFFF;
}

.profile-name {
    font-size: 24px; /* 增大个人资料姓名字体 */
    font-weight: 600;
    color: #1A1A1A;
    margin: 0 0 5px 0;
}

.profile-university {
    font-size: 16px; /* 增大个人资料学校字体 */
    color: #0055FF;
    margin: 0;
    font-weight: 500;
}

.profile-section {
    width: 100%;
    margin-bottom: 16px;
    background-color: #FFFFFF;
    border-radius: 12px;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 85, 255, 0.06);
}

.section-title {
    font-size: 16px; /* 增大右侧部分标题字体 */
    font-weight: 600;
    color: #0055FF;
    margin: 0 0 12px 0;
    padding-bottom: 6px;
    border-bottom: 1px solid rgba(0, 85, 255, 0.1);
}

.section-content {
    font-size: 16px; /* 增大右侧内容字体 */
    color: #333333;
    margin: 0;
    line-height: 1.5;
    font-weight: 500;
}

.contact-info {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.contact-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.contact-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 28px;
    height: 28px;
    background-color: rgba(0, 85, 255, 0.1);
    border-radius: 50%;
}

.contact-item span {
    font-size: 16px; /* 增大联系信息字体 */
    color: #333333;
    font-weight: 500;
}

.products-gallery {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin-top: 10px;
}

.product-item {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    aspect-ratio: 1;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.product-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 8px;
    background: linear-gradient(to top, rgba(0, 0, 0, 0.6), transparent);
    display: flex;
    justify-content: flex-end;
}

.product-price {
    font-size: 12px;
    font-weight: 600;
    color: #FFFFFF;
    background-color: #FF3B30;
    padding: 2px 6px;
    border-radius: 4px;
}

.view-all-btn {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 12px 16px;
    margin-top: 12px;
    background-color: #FFFFFF;
    border: 1px solid rgba(0, 85, 255, 0.2);
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    color: #0055FF;
    cursor: pointer;
    text-align: left;
    transition: all 0.3s ease;
}

.view-all-btn:hover {
    background-color: rgba(0, 85, 255, 0.05);
    border-color: rgba(0, 85, 255, 0.3);
}

.profile-center-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    width: 100%;
    padding: 14px;
    margin: 4px 0 20px 0;
    background-color: #0055FF;
    border: none;
    border-radius: 10px;
    font-size: 15px;
    font-weight: 500;
    color: #FFFFFF;
    cursor: pointer;
    box-shadow: 0 4px 10px rgba(0, 85, 255, 0.3);
    transition: all 0.3s ease;
}

.profile-center-btn:hover {
    background-color: #0044DD;
    transform: translateY(-2px);
    box-shadow: 0 6px 15px rgba(0, 85, 255, 0.4);
}

.settings-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.settings-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px; /* 增大设置项字体 */
    font-weight: 500; /* 加粗设置项字体 */
    color: #333333;
    padding: 12px 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.settings-row:last-child {
    border-bottom: none; /* 最后一个移除分割线 */
}

.toggle-switch {
    position: relative;
    display: inline-block;
    width: 44px;
    height: 24px;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #E5E5EA;
    border-radius: 24px;
    transition: .4s;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 2px;
    bottom: 2px;
    background-color: white;
    border-radius: 50%;
    transition: .4s;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

input:checked + .toggle-slider {
    background-color: #0055FF;
}

input:checked + .toggle-slider:before {
    transform: translateX(20px);
}

.block-user-row {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px 0;
    color: #FF3B30;
    font-weight: 1000;
    cursor: pointer;
    margin-top: 8px;
    font-size: 16px;
    transition: all 0.3s ease;
}


.block-user-icon {
    color: #FF3B30;
}

/* 修改聊天气泡样式 */
.message-bubble.sent {
    background-color: #0055FF;
    color: #FFFFFF;
    border-top-right-radius: 4px;
    align-self: flex-end;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
    border: 2px solid #0044CC;
}

.message-bubble.received {
    background-color: #FFF8F0;
    color: #1F2937;
    border-top-left-radius: 4px;
    align-self: flex-start;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    border: 2px solid #EAEAEA;
}

/* 响应式布局优化 */
@media (max-width: 1400px) {
    .chat-list {
        flex-grow: 3;
    }
    .chat-detail {
        flex-grow: 7;
    }
    .profile-sidebar {
        flex-grow: 4;
    }
}

@media (max-width: 1200px) {
    .chat-list {
        flex-grow: 3;
    }
    .chat-detail {
        flex-grow: 7;
    }
    .profile-sidebar {
        flex-grow: 4;
    }
}

@media (max-width: 900px) {
    .profile-sidebar {
        display: none;
    }
    .chat-list {
        flex-grow: 3;
    }
    .chat-detail {
        flex-grow: 7;
    }
}

@media (max-width: 700px) {
    .chat-list {
        display: none;
    }
    .chat-detail {
        flex-grow: 1;
    }
}

/* 商品消息样式 */
.product-message {
    max-width: 240px;
    width: 240px;
    margin: 16px 0;
    transition: all 0.3s ease;
}

.product-message:hover {
    transform: translateY(-3px);
}

.message-row.sent-row .product-message {
    align-self: flex-end;
}

.message-row:not(.sent-row) .product-message {
    align-self: flex-start;
}

.product-message-content {
    display: flex;
    flex-direction: column;
    background-color: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(239, 239, 239, 0.8);
    transition: all 0.3s ease;
    position: relative;
}

.product-message-content::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0));
    pointer-events: none;
}

.product-message:hover .product-message-content {
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.product-image {
    width: 100%;
    height: 120px;
    object-fit: cover;
    transition: transform 0.4s ease;
}

.product-message:hover .product-image {
    transform: scale(1.05);
}

.product-info {
    padding: 16px;
    position: relative;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    border-top: 1px solid rgba(239, 239, 239, 0.6);
}

.product-header {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
}

.product-name {
    font-size: 15px;
    font-weight: 600;
    color: #000;
    transition: color 0.3s ease;
    margin-right: 8px;
    flex: 1;
}

.product-price-tag {
    display: inline-block;
    padding: 2px 8px;
    font-size: 14px;
    font-weight: 600;
    color: #FF3B30;
    background-color: #FFF8F0;
    border: 1px solid #FFE0B2;
    border-radius: 4px;
    white-space: nowrap;
}

/* 求购商品卡片特殊样式 */
.product-message-content.purchase-request .product-price-tag {
    background-color: #FFF8EE;
    border-color: #FFD8A8;
    color: #f70404;
}

.product-message:hover .product-name {
    color: #5E30EB;
}

.product-price {
    font-size: 15px;
    color: #FF3B30;
    font-weight: 600;
    display: inline-block;
    padding: 2px 8px;
    background-color: rgba(255, 59, 48, 0.1);
    border-radius: 6px;
    margin-top: 6px;
    display: none; /* 隐藏旧的价格标签 */
}

.product-price-inline {
    margin-left: 8px;
    padding: 2px 6px;
    font-size: 14px;
    white-space: nowrap;
}

/* 装饰元素 */
.messages-container::before {
    content: '';
    position: absolute;
    top: 15px;
    right: 15px;
    width: 60px;
    height: 60px;
    border-radius: 10px;
    background: linear-gradient(135deg, rgba(94, 48, 235, 0.08), rgba(94, 48, 235, 0.03));
    z-index: 0;
    opacity: 0.6;
}

.messages-container::after {
    content: '';
    position: absolute;
    bottom: 20%;
    left: 10%;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(255, 59, 48, 0.06), rgba(255, 59, 48, 0.02));
    z-index: 0;
    opacity: 0.5;
}

/* 添加发送消息时的动画 */
.message-row.new-message {
    animation: newMessage 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

@keyframes newMessage {
    0% { opacity: 0; transform: scale(0.8) translateY(20px); }
    100% { opacity: 1; transform: scale(1) translateY(0); }
}

/* 为输入框按钮添加动画 */
.input-action-btn {
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.input-action-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(circle, rgba(124, 58, 237, 0.15) 0%, rgba(124, 58, 237, 0) 70%);
    transform: scale(0);
    opacity: 0;
    transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.input-action-btn:hover::before {
    transform: scale(2.5);
    opacity: 1;
}

.input-action-btn:active {
    transform: scale(0.9);
}

/* 滚动条样式优化 */
.messages-container::-webkit-scrollbar {
    width: 6px;
}

.messages-container::-webkit-scrollbar-track {
    background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
    background-color: rgba(124, 58, 237, 0.2);
    border-radius: 3px;
    transition: all 0.3s ease;
}

.messages-container::-webkit-scrollbar-thumb:hover {
    background-color: rgba(124, 58, 237, 0.4);
}

/* 发送按钮悬停动画 */
.send-btn {
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.send-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 70%);
    transform: scale(0);
    opacity: 0;
    transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    border-radius: inherit;
}

.send-btn:hover::before {
    transform: scale(2.5);
    opacity: 1;
}

.send-btn:active {
    transform: scale(0.95);
}

.send-btn svg {
    transition: transform 0.3s ease;
}

.send-btn:hover svg {
    transform: translateX(2px);
}


.block-action-wrapper {
    display: flex;
    align-items: center;
    gap: 8px; /* 图标和开关间距 */
}

.block-user-warning-icon {
    color: #FF3B30; /* 红色图标 */
    font-size: 16px; /* 图标大小 */
}

/* 覆盖默认开关样式，使其看起来像关闭状态 */
.block-user-switch .toggle-slider {
    background-color: #E5E5EA; /* 强制背景为灰色 */
    cursor: pointer; /* 保持指针样式 */
}

.block-user-switch .toggle-slider:before {
    background-color: white;
    transform: translateX(0); /* 确保滑块在左侧 */
    cursor: pointer; /* 保持指针样式 */
}

/* 确保settings-row的基础样式也应用 */
.settings-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px; /* 增大设置项字体 */
    font-weight: 500; /* 加粗设置项字体 */
    color: #333333;
    padding: 12px 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.settings-row:last-child {
    border-bottom: none;
}

/* 确保基础的 toggle-switch 样式存在 */
.toggle-switch {
    position: relative;
    display: inline-block;
    width: 44px;
    height: 24px;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #E5E5EA; /* 默认关闭状态背景 */
    border-radius: 24px;
    transition: .4s;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 2px;
    bottom: 2px;
    background-color: white;
    border-radius: 50%;
    transition: .4s;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

input:checked + .toggle-slider {
     background-color: #0055FF; /* 这是打开状态的颜色，但在模拟开关中不应出现 */
}

input:checked + .toggle-slider:before {
     transform: translateX(20px); /* 这是打开状态的滑块位置，但在模拟开关中不应出现 */
}

/* 会话列表加载状态 */
.loading-conversations {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    padding: 20px;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    margin-bottom: 16px;
}

.spinner {
    animation: spinnerRotate 2s linear infinite;
    stroke: #007AFF;
    stroke-linecap: round;
}

@keyframes spinnerRotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

@keyframes spinnerDash {
    0% {
        stroke-dasharray: 1, 150;
        stroke-dashoffset: 0;
    }
    50% {
        stroke-dasharray: 90, 150;
        stroke-dashoffset: -35;
    }
    100% {
        stroke-dasharray: 90, 150;
        stroke-dashoffset: -124;
    }
}

.loading-text {
    font-size: 16px; /* 增大加载文本字体 */
    color: #8E8E93;
    text-align: center;
    font-weight: 500;
}

/* 空会话状态 */
.empty-conversations {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    padding: 20px;
}

.empty-icon {
    width: 60px;
    height: 60px;
    margin-bottom: 16px;
    opacity: 0.6;
}

.empty-text {
    font-size: 18px; /* 增大无会话标题字体 */
    font-weight: 600;
    color: #1F2937;
    margin-bottom: 8px;
}

.empty-hint {
    font-size: 16px; /* 增大无会话提示字体 */
    color: #8E8E93;
    text-align: center;
    max-width: 220px;
    line-height: 1.4;
    font-weight: 500;
}

/* 用户资料加载状态 */
.profile-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 0;
    width: 100%;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    margin-bottom: 16px;
}

.spinner {
    animation: spinnerRotate 2s linear infinite;
    stroke: #007AFF;
    stroke-linecap: round;
}

.loading-text {
    font-size: 16px;
    color: #8E8E93;
    text-align: center;
    font-weight: 500;
}

/* 置顶会话和其他会话分隔线 */
.conversations-divider {
    padding: 10px 20px;
    font-size: 13px;
    color: #8E8E93;
    background-color: rgba(248, 249, 250, 0.8);
    border-top: 1px solid rgba(229, 229, 234, 0.5);
    border-bottom: 1px solid rgba(229, 229, 234, 0.5);
    display: flex;
    align-items: center;
}

.conversations-divider span {
    font-size: 14px;
    font-weight: 500;
    color: #8E8E93;
}

/* 置顶会话样式 */
.chat-item.pinned {
    background-color: rgba(151, 117, 250, 0.05);
    border-left: 3px solid #9775FA;
    padding-left: 29px;
}

.chat-item.pinned:hover {
    background-color: rgba(151, 117, 250, 0.08);
}

.chat-item.pinned.active {
    background-color: rgba(124, 58, 237, 0.08);
    border-left-color: #7C3AED;
}

/* 添加求购卡片特殊样式 */
.product-message-content.purchase-request {
    background-color: rgba(255, 248, 240, 0.9);
    border: 1px solid rgba(255, 140, 0, 0.3);
}

.product-message-content.purchase-request .product-name:before {
    content: "[求购] ";
    color: #FF8C00;
}

.product-message-content.purchase-request .product-price {
    background-color: rgba(255, 140, 0, 0.1);
    color: #FF8C00;
}
</style>
